﻿Imports System.Data.Objects
Imports System.Data
Imports System.IO
Imports Cls_Common
Imports VSModel
Imports SecurityService

Partial Class Control_NopThue_Import
    Inherits System.Web.UI.UserControl

    Private Shared ReadOnly log As log4net.ILog = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
    Dim iCountInsertSuccess As Integer = 0
    Dim iCountUpdateSuccess As Integer = 0
    Dim iCountFailt As Integer = 0

#Region "Sub and Function "
    Protected Sub InsertNopTHue(ByVal _dt As DataTable, ByVal irow As Integer)
        Try
            Using data As New VSEntities
                Dim isSuccessFull As Boolean = True
                Dim strMessageErr As String = ""
                Dim strItemCodeErr As String = ""

                Dim strDuplicateErr As String = ""
                Dim _isValid = True
                Dim _MST = _dt(irow)(1).ToString().Trim
                Dim _HoTen = _dt(irow)(2).ToString().Trim
                Dim _DiaChi = _dt(irow)(3).ToString().Trim
                Dim _NganhNghe = _dt(irow)(4).ToString().Trim
                Dim _SoGCN = _dt(irow)(5).ToString().Trim
                Dim _CMND = _dt(irow)(6).ToString().Trim
                Dim _TrangThai = _dt(irow)(7).ToString().Trim
                Dim _NgayCap = _dt(irow)(8).ToString().Trim
                Dim _HuyenId As Integer = Session("HuyenId")
                Dim _curRow = (From q In data.NopThues Where q.MST = _MST And q.HuyenId = _HuyenId Select q).FirstOrDefault
                If Not _curRow Is Nothing Then
                    _curRow.HoTen = _HoTen
                    _curRow.DiaChi = _DiaChi
                    _curRow.NganhNghe = _NganhNghe
                    _curRow.SoGCN = _SoGCN
                    _curRow.CMND = _CMND
                    _curRow.TrangThai = _TrangThai
                    _curRow.NgayCap = StringToDate(_NgayCap)
                    _curRow.Modifier = Session("UserName")
                    _curRow.Modified = Now
                    iCountUpdateSuccess = iCountUpdateSuccess + 1
                Else
                    Dim p As New NopThue
                    With p
                        p.MST = _MST
                        p.HoTen = _HoTen
                        p.DiaChi = _DiaChi
                        p.NganhNghe = _NganhNghe
                        p.SoGCN = _SoGCN
                        p.CMND = _CMND
                        p.TrangThai = _TrangThai
                        p.NgayCap = StringToDate(_NgayCap)
                        p.Creator = Session("UserName")
                        p.Created = Now
                        p.HuyenId = _HuyenId
                        data.NopThues.AddObject(p)
                    End With
                    iCountInsertSuccess = iCountInsertSuccess + 1
                End If
                'Save all Data to DB
                data.SaveChanges()

            End Using
            GC.Collect()
        Catch ex As Exception
            '' Đếm số dòng không thành công
            iCountFailt = iCountFailt + 1
            txtErrorLog.Text = txtErrorLog.Text & String.Format(" - row {0} << {1} >> ", (irow + 1), ex.Message) & Environment.NewLine
        End Try
        divInformation.Visible = True
    End Sub

#End Region

#Region "Event for control "
    Protected Sub btnSave_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnUpload.Click
        ' Xóa đi phần thông tin hiển thị củ
        txtErrorLog.Visible = False
        lblError.Text = ""
        lblSuccess.Text = ""
        lblUpdateSuccess.Text = ""
        txtErrorLog.Text = ""
        If fulData.HasFile Then
            Try
                ''Checkfile extension
                Dim fileExtension As String = If(fulData.FileName.IndexOf(".") <> -1, fulData.FileName.Split(".")(1), "")
                If Not (fileExtension = "xls" Or fileExtension = "xlsx") Then
                    Excute_Javascript("Alertbox('Vui lòng chọn đúng loại file upload(.xls | .xlsx).');", Me.Page, True)
                    Exit Sub
                End If
                iCountInsertSuccess = 0
                iCountUpdateSuccess = 0
                'Upload file len server, vi khi dung fireFox Or Chrom ko lay duoc duong dan thuc su cua file.
                txtFileName.Text = Server.MapPath("~") & "\Uploads\" & fulData.FileName

                'neu ton tai file --> xoa
                If System.IO.File.Exists(txtFileName.Text) = True Then
                    System.IO.File.Delete(txtFileName.Text)
                End If
                'upload file lên Server
                fulData.SaveAs(txtFileName.Text)

                '' Đọc dữ liệu từ file Excel
                Dim _err As String = ""
                Dim _dt = ReadExcelToDT(txtFileName.Text, 0, 0, _err)  'ReadExcelData(txtFileName.Text)
                If _dt.Rows.Count > 0 Then
                    '' Thực hiện Insert dữ liệu vào data base

                    For index As Integer = 0 To _dt.Rows.Count - 1
                        InsertNopTHue(_dt, index)
                    Next

                    '' Hiển thị kết quả INSERT vào database
                    If iCountInsertSuccess > 0 Or iCountUpdateSuccess > 0 Then
                        lblSuccess.Text = String.Format("Thêm mới {0}, cập nhật {1} trong tổng số {2} rows", iCountInsertSuccess, iCountUpdateSuccess, _dt.Rows.Count)
                        Insert_App_Log(String.Format("Thêm mới {0}, cập nhật {1} trong tổng số {2} rows", iCountInsertSuccess, iCountUpdateSuccess, _dt.Rows.Count), Function_Name.QuanLyMST, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))

                    End If

                    If iCountFailt > 0 Then
                        lblError.Text = String.Format("Thất bại {0}/{1} rows ", iCountFailt, _dt.Rows.Count)
                        txtErrorLog.Visible = True
                        Insert_App_Log(String.Format("Cập nhật: {0}/{1} rows. Detail rows index:{2}", iCountFailt, _dt.Rows.Count, txtErrorLog.Text), Function_Name.QuanLyMST, Audit_Type.Create, Request.ServerVariables("REMOTE_ADDR"), Session("UserName"))
                    End If
                Else
                    lblError.Text = "File has no data !" & _err
                End If
            Catch ex As Exception
                lblError.Text = "Import fail " & ex.Message
            Finally
                'Xoa file sau khi insert xong
                'update doi xung qua bang certifiedHouseHold
                Using _data As New VSEntities
                    Dim _HuyenId As Integer = Session("HuyenId")
                    _data.uspNguoiNopThueDoiXung(_HuyenId)
                End Using
                If (File.Exists(txtFileName.Text)) Then
                    File.Delete(txtFileName.Text)
                End If
                txtFileName.Text = ""
                Excute_Javascript("$('#[id*=UpdateProgress1]').hide();", Me.Page, True)
            End Try
        Else
            Excute_Javascript("Alertbox('Vui lòng chọn file dữ liệu Người nộp thuế');$('#[id*=UpdateProgress1]').hide();", Me.Page, True)
        End If
    End Sub

    Protected Sub btnReset_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnReset.Click
        txtErrorLog.Text = ""
        Response.Redirect("Import.aspx", True)
    End Sub

#End Region
End Class
